<?php
namespace app\common\repositories\system;
use app\common\repositories\BaseRepository;
use app\common\dao\system\SystemGroupDataDao as dao;
use FormBuilder\Factory\Elm;
use FormBuilder\Form;
use think\exception\ValidateException;
use think\facade\Route;

/**
 * @mixin dao
 */
class SystemGroupDataRepository extends BaseRepository
{
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    public function create(string $type, array $data, array $fieldRule)
    {
        $this->checkData($data['value'], $fieldRule);
        $data['type'] = $type;

        return $this->dao->create($data);
    }


    public function mUpdate($type, $id, $data, $fieldRule): int
    {
        $this->checkData($data['value'], $fieldRule);
        return $this->dao->mUpdate($type, $id, $data);
    }


    public function checkData(array $data, array $fieldRule)
    {
        foreach ($fieldRule as $rule) {
            if (!isset($data[$rule['field']]) || $data[$rule['field']] === '') {
                throw new ValidateException($rule['name'] . '不能为空');
            }
            if ($rule['type'] === 'number' && $data[$rule['field']] < 0)
                throw new ValidateException($rule['name'] . '不能小于0');
        }
    }

    public function getGroupDataLst(string $type, int $groupId, int $page, int $limit): array
    {
        $query = $this->dao->getGroupDataWhere($type, $groupId);
        $count = $query->count();
        $list = $query->field('group_data_id,value,sort,status,create_time')->page($page, $limit)->select()->toArray();
        foreach ($list as $k => $data) {
            $value = $data['value'];
            unset($data['value']);
            $data += $value;
            $list[$k] = $data;
        }
        return compact('count', 'list');
    }


    public function form(int $groupId, ?int $id = null, array $formData = []): Form
    {
        $fields = app()->make(SystemGroupRepository::class)->fields($groupId);
        $form = Elm::createForm(is_null($id) ? Route::buildUrl('groupDataCreate', compact('groupId'))->build() : Route::buildUrl('groupDataUpdate', compact('groupId', 'id'))->build());
        $rules = [];
        foreach ($fields as $field) {
            if ($field['type'] == 'image') {
                $rules[] = Elm::uploadImage($field['field'], $field['name'], config('app.site_url').Route::buildUrl('configUpload', ['field' => 'file'])->suffix('')->build())->headers(['X-Token' => request()->token()]);
                continue;
            } else if (in_array($field['type'], ['select', 'checkbox', 'radio'])) {
                $options = array_map(function ($val) {
                    [$value, $label] = explode(':', $val, 2);
                    return compact('value', 'label');
                }, explode("\n", $field['param']));
                $rule = Elm::{$field['type']}($field['field'], $field['name'])->options($options);
                if($field['type'] == 'select'){
                    $rule->filterable(true)->prop('allow-create',true);
                }
                $rules[] = $rule;
                continue;
            }
            if ($field['type'] == 'file') {
                $rules[] = Elm::uploadFile($field['field'], $field['name'], Route::buildUrl('configUpload', ['field' => 'file'])->build())->headers(['X-Token' => request()->token()]);
                continue;
            }
            $rules[] = Elm::{$field['type']}($field['field'], $field['name'], '');
        }
        $rules[] = Elm::number('sort', '排序', 0);
        $rules[] = Elm::switches('status', '是否显示', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启');

        $form->setRule($rules);

        return $form->setTitle(is_null($id) ? '添加数据' : '编辑数据')->formData($formData);
    }


    public function updateForm(int $groupId, string $type, int $id)
    {
        $data = $this->dao->getGroupDataWhere($type, $groupId)->where('group_data_id', $id)->find()->toArray();
        $value = $data['value'];
        unset($data['value']);
        $data += $value;
        return $this->form($groupId, $id, $data);
    }

    public function groupData(string $key, string $type, ?int $page = null, ?int $limit = 10)
    {
        /** @var SystemGroupRepository $make */
        $make = app()->make(SystemGroupRepository::class);
        $groupId = $make->keyById($key);
        if (!$groupId) return [];
        return $this->dao->getGroupData($type, $groupId, $page, $limit);
    }


    public function idByData(int $id, string $type)
    {
        $data = $this->dao->mGet($id, $type);
        if (!$data) return;
        return json_decode($data['value']);
    }


    public function groupDataId(string $key, string $type, ?int $page = null, ?int $limit = 10)
    {
        $make = app()->make(SystemGroupRepository::class);
        $groupId = $make->keyById($key);
        if (!$groupId) return [];
        return $this->dao->getGroupDataId($type, $groupId, $page, $limit);
    }
}